package 力扣._2_两数相加;


import 力扣.公用数据结构.ListNode;

public class Solution {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1, p2 = l2, pre_p1 = null, pre_p2 = null;
        int m = 0;  //进位
        while (p1 != null || p2 != null) {
            if (p1 != null && p2 != null) {
                p1.val += p2.val + m;
                m = p1.val / 10;
                p1.val %= 10;
                pre_p1 = p1;
                pre_p2 = p2;
                p1 = p1.next;
                p2 = p2.next;
            } else if (p2 == null) {
                p1.val += m;
                m = p1.val / 10;
                p1.val %= 10;
                pre_p1 = p1;
                p1 = p1.next;
                if (m == 0)
                    break;
            } else {
                pre_p1.next = p2;
                pre_p2.next = p1;
                p1 = pre_p1.next;
                p2 = pre_p2.next;
            }
        }
        if (m != 0)
            pre_p1.next = new ListNode(m);
        return l1;
    }
}